﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace xx
{
	/// <summary>
    /// 物体淡出
    /// </summary>
	public class CoroutineExample01 : MonoBehaviour {
        private MeshRenderer rendererObj;
        //public float fadeSpeed = 1;
        
        private void Start()
        {
            rendererObj = GetComponent<MeshRenderer>();
        }
        public void Update()
        {

        }
        private void OnGUI()
        {
            //IEnumerator coroutine = FadeOut();
            if (GUILayout.Button("敌人死亡"))
            {
                //StartCoroutine(FadeOut());
                StartCoroutine("FadeOut");
                
            }
            if (GUILayout.Button("敌人不死了"))
            {
                //StopCoroutine(FadeOut());//请注意只有StartCoroutine使用一个字符串方法名时，才能用StopCoroutine停用。
                StopCoroutine("FadeOut");
            }

        }
        //匀速淡出
        //private IEnumerator FadeOut()
        //{
        //    //a 1-->0
        //    Color currentColor;
        //    do
        //    {
        //        currentColor = rendererObj.material.color;
        //        currentColor.a -= fadeSpeed * Time.deltaTime;
        //        rendererObj.material.color = currentColor;
        //        yield return null;//等待一帧
        //    } while (currentColor.a > 0);

        //    //transform.position.x = 1;//错误用法
        //    //正确用法，Vector为值类型
        //    //Vector3 pos = transform.position;
        //    //pos.x = 1;
        //    //transform.position = pos;
        //}
        //变速淡出,可应用于变速旋转、移动等
        public AnimationCurve curve;//可视化的数值编辑界面
        public Color targetColor = Color.clear;//目标颜色
        public float time = 1;//时间
        private IEnumerator FadeOut()
        {
            Color originalColor = rendererObj.material.color;
            for (float x = 0; x < 1; x += Time.deltaTime / time)//几秒内变化，time变为几
            {
                float y = curve.Evaluate(x);
                //Lerp作用：数据（0->1）的变化转换为颜色的变化
                rendererObj.material.color = Color.LerpUnclamped(originalColor, targetColor, y);
                //transform.position = Vector3.LerpUnclamped();//变速移动
                //transform.rotation = Quaternion.LerpUnclamped();//变速旋转
                yield return null;
            } 
        }
    }
}

